import { ref } from 'vue';
import { getMarkData as FeatchMarkList } from '@/api/userManage/userManage';
import type { MarkItem } from '@/api/userManage/userManage.d';
import { getRoleList } from "@/api/role/role";
import type * as Type from '@/api/role/role.d'

export default function useUser() {
    const addUserVisibile = ref(false);
    const userFormRef = ref();
    const addUserForm = ref({
        id: null,
        userName: '',
        mobile: '',
        companyId: '',
        roleIds: [],
        code: '',//String(Math.floor((Math.random() * 10) * 100000))
    });

    // 有效的单位集合
    const markValidList = ref<MarkItem[]>([]);
    // 角色的集合
    const roleList = ref<any[]>([]);

    // 获取有效的单位
    const getMarkValidList = async () => {
        const params = {
            status: 1
        };
        const res = await FeatchMarkList(params);
        res && (markValidList.value = res.data);
    };
    // 获取角色
    const setRoleList = async () => {
        const params:Type.RoleListParams = {
            status: 1,//只查启用的
            page: 1,
            pageSize: 10000,
        };
        const res = await getRoleList(params);// api
        res && (roleList.value = res.data.list);
    };

    const handeleAddUserClick = (record?:any) => {
        if(record){//编辑
            addUserForm.value.id = record.id
            addUserForm.value.userName = record.userName
            addUserForm.value.code = record.shortCode
            addUserForm.value.companyId = record.company.id
            addUserForm.value.mobile = record.mobile
            addUserForm.value.roleIds = record.roleList? record.roleList.map(it => it.id) : []
        }else{//新建
            resetUserForm()
        }
        getMarkValidList();
        setRoleList();
        addUserVisibile.value = true;
    };

    const handleEditUser = () => {
        getMarkValidList();
        setRoleList();
        addUserVisibile.value = true;
    }

    const resetUserForm = () => {
        //清空
        addUserForm.value.id = null
        addUserForm.value.userName = ''
        addUserForm.value.mobile = ''
        addUserForm.value.companyId = ''
        addUserForm.value.roleIds = []
        addUserForm.value.code = ''
    }

    return {
        addUserVisibile,
        addUserForm,
        userFormRef,
        markValidList,
        roleList,
        handeleAddUserClick,
        handleEditUser,
    }
}